package cn.lblbc.webbrowser

import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.ImageButton
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.cardview.widget.CardView
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import cn.lblbc.webbrowser.adapters.ImageGridAdapter
import java.io.File

class FavoritesActivity : BaseActivity() {
    
    private lateinit var recyclerView: RecyclerView
    private lateinit var adapter: ImageGridAdapter
    private lateinit var favoritesDir: File
    
    // 批量操作相关UI
    private lateinit var selectionToolbar: LinearLayout
    private lateinit var selectionCountText: TextView
    private lateinit var selectAllButton: ImageButton
    private lateinit var deleteSelectedButton: ImageButton
    private lateinit var cancelSelectionButton: ImageButton
    
    // 空状态相关UI
    private lateinit var emptyStateLayout: LinearLayout
    private lateinit var emptyStateIcon: ImageView
    private lateinit var emptyStateTitle: TextView
    private lateinit var emptyStateMessage: TextView
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_favorites)
        
        // 初始化收藏目录
        favoritesDir = File(getExternalFilesDir(null), "favorites")
        if (!favoritesDir.exists()) {
            favoritesDir.mkdirs()
        }
        
        initViews()
        setupRecyclerView()
        setupListeners()
        loadFavoriteImages()
    }
    
    private fun initViews() {
        recyclerView = findViewById(R.id.favoritesRecyclerView)
        selectionToolbar = findViewById(R.id.selectionToolbar)
        selectionCountText = findViewById(R.id.selectionCountText)
        selectAllButton = findViewById(R.id.selectAllButton)
        deleteSelectedButton = findViewById(R.id.deleteSelectedButton)
        cancelSelectionButton = findViewById(R.id.cancelSelectionButton)
        
        // 空状态视图
        emptyStateLayout = findViewById(R.id.emptyStateLayout)
        emptyStateIcon = findViewById(R.id.emptyStateIcon)
        emptyStateTitle = findViewById(R.id.emptyStateTitle)
        emptyStateMessage = findViewById(R.id.emptyStateMessage)
    }
    
    private fun setupListeners() {
        // 设置返回按钮
        findViewById<ImageButton>(R.id.backButton)?.setOnClickListener {
            if (adapter.isInSelectionMode()) {
                exitSelectionMode()
            } else {
                finish()
            }
        }
        
        // 设置清除所有按钮
        findViewById<ImageButton>(R.id.clearButton)?.setOnClickListener {
            showClearAllConfirmation()
        }
        
        // 全选/全不选按钮
        selectAllButton.setOnClickListener {
            if (adapter.areAllSelected()) {
                adapter.clearSelection()
            } else {
                adapter.selectAll()
            }
        }
        
        // 删除选中按钮
        deleteSelectedButton.setOnClickListener {
            deleteSelectedImages()
        }
        
        // 取消选择按钮
        cancelSelectionButton.setOnClickListener {
            exitSelectionMode()
        }
    }
    
    private fun setupRecyclerView() {
        recyclerView.layoutManager = GridLayoutManager(this, 3)
        adapter = ImageGridAdapter(
            onImageClick = { imageFile ->
                // 点击图片时跳转到全屏查看
                showFullscreenImage(imageFile)
            },
            onImageLongClick = { imageFile ->
                // 长按进入选择模式
                enterSelectionMode()
            },
            onSelectionChanged = { count ->
                // 选择数量变化时更新UI
                updateSelectionUI(count)
            }
        )
        recyclerView.adapter = adapter
    }
    
    private fun loadFavoriteImages() {
        try {
            val favoriteImages = getFavoriteImages()
            adapter.updateImages(favoriteImages)
            updateEmptyState(favoriteImages.isEmpty())
        } catch (e: Exception) {
            e.printStackTrace()
            updateEmptyState(true)
        }
    }
    
    private fun getFavoriteImages(): List<File> {
        return if (favoritesDir.exists()) {
            favoritesDir.listFiles { file ->
                file.isFile && (file.extension.lowercase() in listOf("jpg", "jpeg", "png", "gif", "webp"))
            }?.toList() ?: emptyList()
        } else {
            emptyList()
        }
    }
    
    private fun updateEmptyState(isEmpty: Boolean) {
        if (isEmpty) {
            recyclerView.visibility = View.GONE
            emptyStateLayout.visibility = View.VISIBLE
            
            emptyStateIcon.setImageResource(R.drawable.ic_favorite_border)
            emptyStateTitle.text = "暂无收藏图片"
            emptyStateMessage.text = "在图片查看器中点击收藏按钮来收藏图片"
        } else {
            recyclerView.visibility = View.VISIBLE
            emptyStateLayout.visibility = View.GONE
        }
    }
    
    private fun showFullscreenImage(imageFile: File) {
        try {
            val allImages = getFavoriteImages()
            val currentPosition = allImages.indexOf(imageFile)
            
            if (currentPosition >= 0) {
                val intent = Intent(this, ImageViewerActivity::class.java)
                intent.putExtra("image_files", ArrayList(allImages))
                intent.putExtra("current_position", currentPosition)
                startActivity(intent)
            }
        } catch (e: Exception) {
            e.printStackTrace()
            Toast.makeText(this, "无法打开图片查看器", Toast.LENGTH_SHORT).show()
        }
    }
    
    private fun enterSelectionMode() {
        adapter.enterSelectionMode()
        selectionToolbar.visibility = View.VISIBLE
        updateSelectionUI(0)
    }
    
    private fun exitSelectionMode() {
        adapter.exitSelectionMode()
        selectionToolbar.visibility = View.GONE
    }
    
    private fun updateSelectionUI(selectedCount: Int) {
        selectionCountText.text = "已选择 $selectedCount 项"
        deleteSelectedButton.isEnabled = selectedCount > 0
        deleteSelectedButton.alpha = if (selectedCount > 0) 1.0f else 0.5f
        
        // 更新全选按钮状态
        if (adapter.areAllSelected()) {
            selectAllButton.setImageResource(R.drawable.ic_select_none)
            selectAllButton.contentDescription = "全部不选"
        } else {
            selectAllButton.setImageResource(R.drawable.ic_select_all)
            selectAllButton.contentDescription = "全选"
        }
    }
    
    private fun deleteSelectedImages() {
        val selectedImages = adapter.getSelectedImages()
        if (selectedImages.isEmpty()) {
            Toast.makeText(this, "请选择要删除的图片", Toast.LENGTH_SHORT).show()
            return
        }
        
        AlertDialog.Builder(this)
            .setTitle("删除收藏图片")
            .setMessage("确定要删除选中的 ${selectedImages.size} 张收藏图片吗？")
            .setPositiveButton("删除") { _, _ ->
                performDeleteSelectedImages(selectedImages)
            }
            .setNegativeButton("取消", null)
            .show()
    }
    
    private fun performDeleteSelectedImages(imagesToDelete: List<File>) {
        try {
            var deletedCount = 0
            imagesToDelete.forEach { file ->
                if (file.exists() && file.delete()) {
                    deletedCount++
                }
            }
            
            exitSelectionMode()
            loadFavoriteImages()
            
            Toast.makeText(this, "已删除 $deletedCount 张图片", Toast.LENGTH_SHORT).show()
            
        } catch (e: Exception) {
            e.printStackTrace()
            Toast.makeText(this, "删除失败: ${e.message}", Toast.LENGTH_SHORT).show()
        }
    }
    
    private fun showClearAllConfirmation() {
        val totalCount = getFavoriteImages().size
        if (totalCount == 0) {
            Toast.makeText(this, "没有收藏图片可清除", Toast.LENGTH_SHORT).show()
            return
        }
        
        AlertDialog.Builder(this)
            .setTitle("清除所有收藏")
            .setMessage("确定要清除所有 $totalCount 张收藏图片吗？")
            .setPositiveButton("清除") { _, _ ->
                clearAllFavorites()
            }
            .setNegativeButton("取消", null)
            .show()
    }
    
    private fun clearAllFavorites() {
        try {
            val favoriteImages = getFavoriteImages()
            var deletedCount = 0
            favoriteImages.forEach { file ->
                if (file.exists() && file.delete()) {
                    deletedCount++
                }
            }
            loadFavoriteImages()
            Toast.makeText(this, "已清除 $deletedCount 张收藏图片", Toast.LENGTH_SHORT).show()
        } catch (e: Exception) {
            e.printStackTrace()
            Toast.makeText(this, "清除收藏失败: ${e.message}", Toast.LENGTH_SHORT).show()
        }
    }
    
    override fun onResume() {
        super.onResume()
        // 每次显示时重新加载图片
        loadFavoriteImages()
    }
    
    @Deprecated("Deprecated in Java")
    override fun onBackPressed() {
        if (adapter.isInSelectionMode()) {
            exitSelectionMode()
        } else {
            super.onBackPressed()
        }
    }
}